#include "threadpool.h"

struct threadpool *create_threadpool(int threads, int queue_length, void *(*con)(void *))
{
    struct threadpool *pool = malloc(sizeof(struct threadpool));
    int ret;

    pool->tids = malloc(sizeof(pthread_t) * threads);
    pool->que = create_queue();
    pool->threads = threads; 

    sem_init(&pool->semw, 0, queue_length);
    sem_init(&pool->semr, 0, 0);
    pthread_mutex_init(&pool->mutex, NULL);

    for (int i = 0; i < threads; i++)
    {
        ret = pthread_create(&pool->tids[i], NULL, con, pool);
        if (ret != 0)
        {
            perror("pthread_create");
            return NULL;
        }
    }

    return pool;
}

void destroy_threadpool(struct threadpool *pool)
{
    for (int i = 0; i < pool->threads; i++) // 使用存储的线程数量
    {
        if (sem_post(&pool->semw) != 0)
        {
            perror("sem_post");
        }
    }
    if (sem_post(&pool->semr) != 0)
    {
        perror("sem_post");
    }
    for (int i = 0; i < pool->threads; i++)
    {
        if (pthread_join(pool->tids[i], NULL) != 0)
        {
            perror("pthread_join");
        }
    }
    free(pool->tids);
    destroy_queue(pool->que);
    sem_destroy(&pool->semr);
    sem_destroy(&pool->semw);
    pthread_mutex_destroy(&pool->mutex);
    free(pool);
}
